﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public enum Arrangement
{
	Horizontal,
	Vertical,
}
public class SimpleGrid : MonoBehaviour 
{
    public Arrangement arrangement = Arrangement.Horizontal;
    public int maxPerLine = 1;

    /// <summary>
    /// The width of each of the cells.
    /// </summary>

    public float cellWidth = 200f;

    /// <summary>
    /// The height of each of the cells.
    /// </summary>

    public float cellHeight = 200f;

	public float paddingX = 10f;
	public float paddingY = 10f;

    public List<GameObject> childs = new List<GameObject>();

    public Vector3 GetPositionByIndex(int index)
    {
        int indexX, indexY;
        if (arrangement == Arrangement.Horizontal)
        {
            indexX = index / maxPerLine;
            indexY = index % maxPerLine;
        }
        else
        {
            indexY = index / maxPerLine;
            indexX = index % maxPerLine;
        }
        return new Vector3(indexX * cellWidth,-indexY * cellHeight,0f);
    }

    public GameObject GetByPosition(float x,float y)
    {
        int xIndex = (int)((x  / cellWidth) + 0.5f);
        int yIndex = (int)((y / -cellHeight) + 0.5f);
		if(xIndex<0 || yIndex< 0)
		{
			return null;
		}
        int index;
		int perLine = Mathf.Max(maxPerLine,1);
        if (arrangement == Arrangement.Horizontal)
        {
			if (yIndex > perLine)
            {
                return null;
            }
			index = xIndex * perLine + yIndex;
        }
        else
        {
			if (xIndex > perLine)
            {
                return null;
            }
			index = yIndex * perLine + xIndex;
        }
        if (childs.Count < index - 1 || index < 0 || index >= childs.Count )
        {
            return null;
        }
        else
        {
			GameObject res = childs[index].gameObject;
			float deltaX = Mathf.Abs(res.transform.localPosition.x - x);
			if(deltaX > cellWidth * 0.5f - paddingX)
			{
				return null;
			}
			float deltaY = Mathf.Abs(res.transform.localPosition.y - y);
			if(deltaY > cellHeight * 0.5f - paddingY)
			{
				return null;
			}
			return res;
        }
    }
    public void OnClickX(Vector3 position)
    {
        Vector3 pos = transform.InverseTransformPoint(position);
        GameObject childObj = GetByPosition(pos.x,pos.y);
        if (childObj != null && !hasDrag)
        {
            childObj.SendMessage("OnClick",SendMessageOptions.DontRequireReceiver);
        }
    }

	private bool hasDrag = false;

	public void OnDragX(Vector3 position, Vector2 delta)
	{
		Vector3 pos = transform.InverseTransformPoint(position);
		GameObject childObj = GetByPosition(pos.x, pos.y);
		hasDrag = true;
		if (childObj != null)
		{
			childObj.SendMessage("OnDrag", delta, SendMessageOptions.DontRequireReceiver);
		}
	}

    private GameObject currentPressObj;
    public void OnPressX(Vector3 position, bool isPress)
    {
        Vector3 pos = transform.InverseTransformPoint(position);
        GameObject childObj = GetByPosition(pos.x, pos.y);
        if (isPress)
        {
			hasDrag = false;
//			if(childObj != null)
//			{
//				currentPressObj = null;
//				childObj.collider.enabled = true;
//				UICamera.current.Update();
//				childObj.collider.enabled = false;
//			}
            if (currentPressObj != null)
            {
                currentPressObj.SendMessage("OnPress", false, SendMessageOptions.DontRequireReceiver);
            }
            currentPressObj = childObj;
            if (childObj != null)
            {
				//UICamera.hoveredObject = currentPressObj;
                currentPressObj.SendMessage("OnPress", true, SendMessageOptions.DontRequireReceiver);
            }
        }
        else
        {

            if (currentPressObj != null)
            {
				currentPressObj.SendMessage("OnPress", false, SendMessageOptions.DontRequireReceiver);
            }
            currentPressObj = null;
        }
    }

    public void AddChild(GameObject child)
    {
        childs.Add(child);
        child.transform.parent = transform;
        child.transform.localScale = Vector3.one;
        child.transform.localPosition = GetPositionByIndex(childs.Count - 1);
    }

    public void Reposition()
    {
        for (int i = 0; i < childs.Count;++i)
        {
            childs[i].transform.localPosition = GetPositionByIndex(i);
        }
    }
    public void Reposition(int index)
    {
        for (int i = index; i < childs.Count; ++i)
        {
            childs[i].transform.localPosition = GetPositionByIndex(i);
        }
    }
    
    public void RepositionActive ()
    {
    	int nIndex=0;
    	for (int i=0; i<childs.Count; i++)
    	{
			if (childs[i].activeSelf)
			{
				childs[i].transform.localPosition = GetPositionByIndex(nIndex++);
			}
    	}
    }

    public void RepositionActiveChangeOrder(int count)
    {
        int nIndex = 0;
        List<GameObject> activeList = new List<GameObject>();
        List<GameObject> deactiveList = new List<GameObject>();
        for (int i = 0; i < childs.Count; i++)
        {
            if (childs[i].activeSelf && nIndex < count)
            {
                activeList.Add(childs[i]);
                nIndex++;
            }
            else
            {
                childs[i].SetActive(false);
                deactiveList.Add(childs[i]);
            }
        }
        childs.Clear();
        nIndex = 0;
        foreach (GameObject activeChild in activeList)
        {
            activeChild.transform.localPosition = GetPositionByIndex(nIndex++);
            childs.Add(activeChild);
        }
        foreach (GameObject deactiveChild in deactiveList)
        {
            childs.Add(deactiveChild);
        }
        activeList.Clear();
        deactiveList.Clear();
    }
}
